package com.richfit.barcodesystem_cczt.activitis;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;

import androidx.appcompat.app.AlertDialog;

import com.google.gson.reflect.TypeToken;
import com.richfit.barcodesystem_cczt.R;
import com.richfit.barcodesystem_cczt.activitis.adapters.BottomDialogMenuAdapter;
import com.richfit.barcodesystem_cczt.activitis.base.BaseActivity;
import com.richfit.barcodesystem_cczt.activitis.model.UpdateInfo;
import com.richfit.barcodesystem_cczt.activitis.model.base.Result;
import com.richfit.barcodesystem_cczt.activitis.model.login.BottomMenuEntity;
import com.richfit.barcodesystem_cczt.activitis.model.login.LoginEntity;
import com.richfit.barcodesystem_cczt.activitis.model.login.LoginInfoEntity;
import com.richfit.barcodesystem_cczt.appcliation.MyAppcliation;
import com.richfit.barcodesystem_cczt.databinding.ActivityLoginBinding;
import com.richfit.barcodesystem_cczt.databinding.DialogIpManagerBinding;
import com.richfit.barcodesystem_cczt.network.OkHttpUtils;
import com.richfit.barcodesystem_cczt.network.download.DownloadProgressListener;
import com.richfit.barcodesystem_cczt.network.download.DownloadUtil;
import com.richfit.barcodesystem_cczt.utils.Update;
import com.richfit.barcodesystem_cczt.utils.Urls;
import com.richfit.barcodesystem_cczt.utils.dialog.DialogHelper;
import com.richfit.barcodesystem_cczt.utils.sharedPreferences.DatabaseHelper;
import com.richfit.barcodesystem_cczt.utils.toast.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * create by cl 20211106
 */
public class Login extends BaseActivity {

    private static final String TAG = "Login";
    /**
     * 视图绑定
     */
    private ActivityLoginBinding binding;

    public final static int convertToInt(Object value, int defaultValue) {
        if (value == null || "".equals(value.toString().trim())) {
            return defaultValue;
        }
        try {
            return Integer.valueOf(value.toString());
        } catch (Exception e) {
            try {
                return Double.valueOf(value.toString()).intValue();
            } catch (Exception e1) {
                return defaultValue;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获取本地存储数据
        bo = DatabaseHelper.getBaseBO();
        Intent intent = getIntent();
        int type = intent.getIntExtra("type", -1);
        //type:1 登录过期或者退出登录，重新加载登录页面
        //登录后，如果session存在缓存，直接进入菜单页面。调用接口返回结果是未登录，直接跳到登录页面重新登录
        if (TextUtils.isEmpty(bo.cookie) || type == 1) {
            binding = ActivityLoginBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());
            updateTask();
        } else {
            //本地有缓存，直接进入主页
            intent = new Intent();
            intent.setClass(Login.this, Home.class);
            startActivity(intent);
            finish();
        }

    }

    private void init() {
        initView();
        getCode();
        initData();
        chooseLogin();
    }

    private void initView() {
        //加载保存的账号
        if (bo.account != null && !"".equals(bo.account)) {
            binding.EdtAccount.setText(bo.account);
            binding.EdtAccount.setSuffixIconVisible(binding.EdtAccount.length() > 0);
        }
        //加载保存的密码,如果记住密码的话
        if ("1".equals(bo.remembered) && bo.password != null && !"".equals(bo.password)) {
            binding.EdtPassword.setText(bo.password);
            binding.EdtPassword.setSuffixIconVisible(binding.EdtPassword.length() > 0);

        }
        //是否记住密码，单选框
        binding.cbRemember.setChecked("1".equals(bo.remembered) ? true : false);
        binding.floatingButton.setOnClickListener(v -> showChooseDialog());

    }

    void initData() {
        //三个输入框，点击右边图片，清空数据项
        binding.EdtAccount.setOnRichAutoEditTouchListener((view, text) -> binding.EdtAccount.setText(""));
        binding.EdtPassword.setOnRichAutoEditTouchListener((view, text) -> binding.EdtPassword.setText(""));
        binding.EdtCode.setOnRichAutoEditTouchListener((view, text) -> binding.EdtCode.setText(""));
        binding.ImgCode.setOnClickListener(v -> {
            //点击验证码区域，重新加载验证码
            binding.EdtCode.setText("");
            getCode();
        });
        //记住密码选项
        binding.cbRemember.setOnCheckedChangeListener((buttonView, isChecked) -> {
            bo.remembered = isChecked ? "1" : "0";
        });
        binding.btnLogin.setOnClickListener(v -> {
            //验证账号密码验证码是否输入
            checkLogin();
        });
    }

    /**
     * 获取验证码方法
     */
    void getCode() {
        //获取验证码图片
        DialogHelper dialogHelper = new DialogHelper(this);
        dialogHelper.showLoadingDialog("正在获取验证码");
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        try {
            okHttpUtils.doGetForCode(Urls.URL_LOGIN_CODE, new OkHttpUtils.NetCallBack() {
                @Override
                public void onSuccess(Result result) {
                    dialogHelper.dismissDialog();
                    if (result.getData() != null) {
                        Bitmap bitmap = (Bitmap) result.getData();
                        binding.ImgCode.setImageBitmap(bitmap);
                        bo.cookie = result.getCookie();
                        //本地缓存cookie
                        DatabaseHelper.updateBo(bo);
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    dialogHelper.dismissDialog();
                    ToastUtil.showTextShort("获取验证码失败！", binding.getRoot());
                }
            });
        } catch (Exception e) {
            Log.i(TAG, "getImgCode: " + e.getMessage());
            ToastUtil.showTextShort(e.getMessage());
        } finally {
            dialogHelper.dismissDialog();
        }
    }

    /**
     * 检查登录账号密码验证码是否为空，并且去掉前后空格
     */
    void checkLogin() {
        String account = binding.EdtAccount.getText().toString().trim();
        String psd = binding.EdtPassword.getText().toString().trim();
        String code = binding.EdtCode.getText().toString().trim();
        if ("".equals(account)) {
            ToastUtil.showTextShort(MyAppcliation.context.getString(R.string.err_account));
        } else if ("".equals(psd)) {
            ToastUtil.showTextShort(MyAppcliation.context.getString(R.string.err_password));
        } else if ("".equals(code)) {
            ToastUtil.showTextShort(MyAppcliation.context.getString(R.string.err_code));
        } else {
            //登录
            login(account, psd, code);

        }
    }

    /**
     * 登录
     *
     * @param account
     * @param psd
     * @param code
     */
    void login(String account, String psd, String code) {

        List<LoginInfoEntity> list;
        //获取已经存在的账号，账号不存在的新创建列表
        if (TextUtils.isEmpty(bo.accounts)) {
            list = new ArrayList<>();
        } else {
            list = gson.fromJson(bo.accounts, new TypeToken<List<LoginInfoEntity>>() {
            }.getType());
        }
        LoginInfoEntity loginInfoEntity = new LoginInfoEntity();
        DialogHelper dialogHelper = new DialogHelper(this);
        dialogHelper.showLoadingDialog("正在登录");
        bo.maps = Urls.getDefaultConfigrationMap();
        bo.maps.put("name", account);
        bo.maps.put("password", psd);
        bo.account = account;
        //添加账号
        loginInfoEntity.setAccount(account);
        //是否记住密码
        loginInfoEntity.setRemembered(bo.remembered);
        if ("1".equals(bo.remembered)) {
            bo.password = psd;
            loginInfoEntity.setPassword(psd);
        } else {
            bo.password = "";
            loginInfoEntity.setPassword("");
        }
        //账号密码存入列表
        Boolean isVerb = false;
        for (LoginInfoEntity loginInfoEntity1 : list) {
            //判断是否有重复的账号
            if (account.equals(loginInfoEntity1.getAccount())) {
                isVerb = true;
                break;
            }
        }
        if (!isVerb) {
            //没有重复项，添加进缓存
            list.add(loginInfoEntity);
        }
        //转为json
        bo.accounts = gson.toJson(list);
        //数据保存到缓存
        DatabaseHelper.updateBo(bo);
        bo.maps.put("captcha", code);
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        okHttpUtils.doPostMap(Urls.URL_LOGIN, bo.cookie, bo.maps, new OkHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Result result) {
                dialogHelper.dismissDialog();
                String data = gson.toJson(result.getData());
                List<LoginEntity> loginEntities = gson.fromJson(data, new TypeToken<List<LoginEntity>>() {
                }.getType());
                //返回的数据都是数组类型，默认取第一项
                LoginEntity loginEntity = loginEntities.get(0);
                bo.cookie = loginEntity.getName() + "=" + loginEntity.getValue();
                DatabaseHelper.updateBo(bo);
                ToastUtil.showTextLong("登录成功");
                //跳转到菜单页面，关闭登录页面
                Intent intent = new Intent();
                intent.setClass(Login.this, Home.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onFailure(Exception e) {

                binding.EdtCode.setText("");
                dialogHelper.dismissDialog();
            }
        });
    }

    /**
     * 显示底部弹窗列表
     */
    private void showChooseDialog() {
        View rootView = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_menu, null);
        GridView menu = (GridView) rootView.findViewById(R.id.gd_menus);
        ArrayList<BottomMenuEntity> items = new ArrayList<>();
        BottomMenuEntity item = new BottomMenuEntity();
        item.setMenuName("App基本信息");
        item.setMenuImageRes(R.mipmap.icon_data_submit);
        items.add(item);

        item = new BottomMenuEntity();
        item.setMenuName("修改IP");
        item.setMenuImageRes(R.mipmap.icon_transfer);
        items.add(item);

        item = new BottomMenuEntity();
        item.setMenuName("检查更新");
        item.setMenuImageRes(R.mipmap.icon_update);
        items.add(item);


        BottomDialogMenuAdapter adapter = new BottomDialogMenuAdapter(this, items);
        menu.setAdapter(adapter);

        final Dialog dialog = new Dialog(this, R.style.MaterialDialogSheet);
        dialog.setContentView(rootView);
        dialog.setCancelable(true);
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.show();

        menu.setOnItemClickListener((adapterView, view, position, id) -> {
            switch (position) {
                case 0:
                    showAppBasicInfo();
                    break;
                case 1:
                    showEditIpDialog();
                    break;
                case 2:
                    updateTask();
                    break;
                default:
                    break;
            }
            dialog.dismiss();
        });
    }

    /**
     * app信息
     */
    private void showAppBasicInfo() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        StringBuffer sb = new StringBuffer();
        sb.append("当前使用的系统")
                .append("在线系统")
                .append("\n")
                .append("当前版本号:")
                .append("V(")
                .append(Update.getVersionCode(this))
                .append(")")
                .append("\n")
                .append("服务器地址:")
                .append(bo.requestUrl);
        builder.setTitle("App信息查看")
                .setMessage(sb.toString())
                .show();
    }

    /**
     * 修改ip
     */
    private void showEditIpDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置新的IP");
        DialogIpManagerBinding ipManagerBinding = DialogIpManagerBinding.inflate(getLayoutInflater());

        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        ipManagerBinding.getRoot().setLayoutParams(lp);
        ipManagerBinding.tvOldIp.setText("当前的ip是:" + bo.requestUrl);
        builder.setView(ipManagerBinding.getRoot());
        builder.setPositiveButton("确定", (dialogInterface, i) -> {
            dialogInterface.dismiss();
            prepareEditIp(ipManagerBinding);

        }).setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss()).show();

    }

    private void prepareEditIp(DialogIpManagerBinding ipManagerBinding) {

        if (!checkIp(ipManagerBinding.ip1, ipManagerBinding.ip2, ipManagerBinding.ip3, ipManagerBinding.ip4)) {
            ToastUtil.showTextShort("您输入的IP不合理", ipManagerBinding.getRoot());
            return;
        }

        final String port = ipManagerBinding.etPort.getText().toString().trim();
        if (TextUtils.isEmpty(port)) {
            ToastUtil.showTextShort("请输入端口号", ipManagerBinding.getRoot());
            return;
        }
        final StringBuffer sb = new StringBuffer();
        sb.append(Urls.getHttp(0))
                .append(ipManagerBinding.ip1.getText().toString().trim())
                .append(".")
                .append(ipManagerBinding.ip2.getText().toString().trim())
                .append(".")
                .append(ipManagerBinding.ip3.getText().toString().trim())
                .append(".")
                .append(ipManagerBinding.ip4.getText().toString().trim())
                .append(":")
                .append(port);
        final String newUrl = sb.toString();
        if (TextUtils.isEmpty(newUrl)) {
            ToastUtil.showTextShort("IP为空", ipManagerBinding.getRoot());
            return;
        }
        bo.requestUrl = newUrl;
        DatabaseHelper.updateBo(bo);
        bo = DatabaseHelper.getBaseBO();
        return;
    }

    /**
     * 检查IP是否符合规范
     *
     * @param ets
     * @return
     */
    private boolean checkIp(EditText... ets) {
        for (EditText et : ets) {
            int ip = convertToInt(et.getText().toString().trim(), 0);
            if (ip <= 0 || ip > 255) {
                return false;
            }
        }
        return true;
    }

    /**
     * 选择已保存的账号进行登录
     */
    private void chooseLogin() {
        if (TextUtils.isEmpty(bo.accounts)) {
            return;
        }
        List<LoginInfoEntity> list = gson.fromJson(bo.accounts, new TypeToken<List<LoginInfoEntity>>() {
        }.getType());
        List<String> list1 = new ArrayList<>();
        for (LoginInfoEntity loginInfoEntity : list) {
            list1.add(loginInfoEntity.getAccount());
        }

        binding.EdtAccount.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, list1));
        binding.EdtAccount.setOnClickListener(v -> {
            binding.EdtAccount.showDropDown();
        });
        binding.EdtAccount.setOnItemClickListener((parent1, view, position, id) -> {
            ToastUtil.showTextShort(list.get(position).getAccount());
            binding.EdtPassword.setText(list.get(position).getPassword());
            binding.cbRemember.setChecked("1".equals(list.get(position).getRemembered()) ? true : false);
        });
    }

    /**
     * 重新打开页面后获取上一个页面传值
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == 101) {
            init();
        }
    }

    /**
     * app更新
     */
    protected void updateTask() {
        DialogHelper dialogHelper = new DialogHelper(this);
        dialogHelper.showLoadingDialog("正在检查更新");
        bo.maps = Urls.getDefaultConfigrationMap();
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        okHttpUtils.doGet(Urls.URL_UPDATE, bo.cookie, new OkHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Result result) {
                dialogHelper.dismissDialog();
                if (result.getData() != null) {
                    String data = gson.toJson(result.getData());
                    UpdateInfo update = gson.fromJson(data, UpdateInfo.class);
                    //判断是否需要更新
                    update(update);
                } else {
                    init();
                }
            }

            @Override
            public void onFailure(Exception e) {
                dialogHelper.dismissDialog();
                init();
            }
        });
    }

    /**
     * 判断是否更新app
     *
     * @param update
     */
    public void update(UpdateInfo update) {
        if (Update.isNeedUpdate(update.getVersion(), this)) {
            loadNewVersionAlertDiaLog(update);
        } else {
            init();
            ToastUtil.showTextShort("已经是最新版本！");
        }
    }

    /**
     * 更新提示框
     *
     * @param update
     */
    public void loadNewVersionAlertDiaLog(UpdateInfo update) {

        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("更新说明");
        alert.setMessage(update.getMsg());
        /**
         * 点击弹窗之外区域，弹框不消失
         */
        alert.setCancelable(false);
        alert.setPositiveButton("立即更新", (dialog, which) -> {
            try {
                download(this, update, "app.apk");
            } catch (Exception e) {
                new AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("下载文件出错" + e.getMessage())
                        .setPositiveButton("确定", (dialog1, which1) -> {
                            if (update.getIsPower() == 0) {
                                init();
                            } else {
                                finish();
                            }
                        })
                        .create()
                        .show();
            }

        });
        if (update.getIsPower() == 0) {
            alert.setNegativeButton("暂不更新", (dialog, which) -> {
                //如果不更新，则进入正常登录流程
                init();
            });
        }
        alert.create();
        alert.show();
    }

    /**
     * app下载
     *
     * @param mContext
     * @param update
     * @param fileName
     */
    public void download(Context mContext, UpdateInfo update, String fileName) {
        binding.progressbar.setVisibility(View.VISIBLE);
        DownloadUtil.download(mContext, update.getUrl(), fileName, new DownloadProgressListener() {
            @Override
            public void onDownloadProgress(long sumReaded, long content, boolean done) {
                binding.progressbar.setProgress((int) (sumReaded * 100 / content));
            }

            @Override
            public void onDownloadResult(String filePath, long sumReaded, long content, boolean done) {
                if (done) {
                    runOnUiThread(() -> {
                        binding.progressbar.setVisibility(View.GONE);
                        ToastUtil.showTextLong("下载完成，开始安装！");
                        DownloadUtil.installAPK(mContext, filePath, fileName);
                    });
                } else {
                    runOnUiThread(() -> {
                        binding.progressbar.setVisibility(View.GONE);
                        ToastUtil.showTextShort("下载不完整！");
                        //如果不更新，则进入正常登录流程
                        init();
                    });
                }
            }

            @Override
            public void onFailResponse() {

                runOnUiThread(() -> {
                    binding.progressbar.setVisibility(View.GONE);
                    ToastUtil.showTextShort("下载失败！");
                    //如果不更新，则进入正常登录流程
                    init();
                });

            }
        });

    }
}